package com.mlx.meng.tool;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.*;

public class DataPermissionUtil {

    private static final String foreignKeysFieldRegex = "^([a-zA-z_])[a-zA-z0-9_]{0,}:[a-zA-z_][a-zA-z0-9_]{0,}:([a-zA-z_][a-zA-z0-9_]{0,})$";

    public static boolean checkForeignKeyFormat(String foreignKey){
        if (foreignKey == null){
            return false;
        }
        return foreignKey.matches(foreignKeysFieldRegex);
    }


    // 获取类定义的所有非静态属性map，键值为属性名
    public static Map<String, Field> gainClassField(Class<?> aClass){
        Map<String, Field> fieldMap = new HashMap<>();
        Field[] fields = aClass.getDeclaredFields();
        for (Field f : fields){
            if (!(Modifier.isStatic(f.getModifiers()))){
                f.setAccessible(true);
                fieldMap.put(f.getName(), f);
            }
        }
        return fieldMap;
    }


    public static boolean isEmpty(Object obj){
        if (obj == null){
            return true;
        }
        if (obj instanceof String){
            return "".equals(obj);
        }
        if (obj instanceof Object[]){
            return ((Object[]) obj).length == 0;
        }
        if (obj instanceof Collection){
            return ((Collection<?>) obj).isEmpty();
        }
        if (obj instanceof Map){
            return ((Map<?, ?>) obj).isEmpty();
        }
        return false;
    }

    public static boolean isNotEmpty(Object obj){
        return !(isEmpty(obj));
    }


    public static <T> PageAuxiliary<T> buildPage(List<T> dataList, Integer pageNum, Integer pageSize){

        PageAuxiliary<T> page = new PageAuxiliary<>();

        // 如果数据为空，返回一个空页面
        if (isEmpty(dataList)){
            page.setTotal(0);
            page.setList(new ArrayList<>());
            return page;
        }

        // 设置页面默认值
        if (isEmpty(pageNum) || pageNum <= 0){
            pageNum = 1;
        }
        if (isEmpty(pageSize) || pageSize <= 0){
            pageSize = 10;
        }

        // 计算开始行和结束行
        int startRow = (pageNum - 1) * pageSize;
        int endRow = startRow + pageSize;

        // 获取数据量
        int size = dataList.size();

        // 开始行大于数据量，返回空页面
        if (startRow >= size){
            page.setTotal(size);
            page.setList(new ArrayList<>());
            return page;
        }

        // 末尾行大于数据量，末尾行为数据量
        if (endRow > size){
            endRow = size;
        }

        List<T> list = dataList.subList(startRow, endRow);

        page.setTotal(size);
        page.setList(list);

        return page;
    }

}
